﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Motorbike.Model;
using Motorbike.BLL;
using WinForm.Validation;

namespace Motorbike.APP.Forms
{
    public partial class LoginForm : AbsBaseForm
    {
        private IntegrateValidator formValidator;

        public LoginForm()
        {
            InitializeComponent();

            formValidator = WinFormIntegrateValidator.CreateInstance().AddNotBlankFieldValidator(loginName, loginPassword);
        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (formValidator.Validate())
            {
                User loginUser = BllServiceFactory.Instance.SystemService.GetUser(loginName.Text);
                if (null == loginUser)
                {
                    ShowWarning("系统中不存在该用户：" + loginName.Text);
                }
                else if (!String.Equals(loginPassword.Text, loginUser.Password))
                {
                    ShowWarning("密码不正确，请重新输入！");
                }
                else
                {
                    ApplicationContext.Instance.CurrentUser = loginUser;
                    LoginLog log = BllServiceFactory.Instance.SystemService.WriteLoginLog(loginUser);
                    ApplicationContext.Instance.CurrentLoginLog = log;

                    this.DialogResult = DialogResult.OK;
                }
            }
        }

        private User Login(string userCode, string password)
        {
            return null;
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            if (BllServiceFactory.Instance.SystemService.GetUserCount() == 0)
            {
                DialogResult result = Confirm("当前系统还没有创建用户，是否现在创建初始化用户!?\n该初始化用户将作为系统管理员!");
                if (DialogResult.Yes == result)
                {
                    UserAddForm frmAddUser = new UserAddForm();
                    this.Hide();
                    frmAddUser.ShowDialog();
                    this.loginName.Text = frmAddUser.CurrentUser.Code;
                    //this.loginPassword.Text = frmAddUser.CurrentUser.Password;
                }
                else
                {
                    ShowError("没得用户你玩毛线呀......");
                }
            }
        }
    }
}
